package com.yantong.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yantong.enums.MemberStoresApplicationWayEnum;
import com.yantong.constant.*;
import com.yantong.exception.BDException;
import com.yantong.mapper.CentreIndustryMapper;
import com.yantong.mapper.MemberMapper;
import com.yantong.pojo.*;
import com.yantong.service.*;
import com.yantong.utils.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 操作Member服务
 *
 * @author xiangyi
 * @version V1.0.0
 * @Description:
 * Copyright: Copyright (c) 2018
 * @date 2018年9月3日 下午6:55:16
 * @since 3.0
 */
@Service
public class RegCommanderServiceImpl implements RegCommanderService {

	private static final Logger logger = LoggerFactory.getLogger(RegCommanderServiceImpl.class);

	@Autowired
	private MemberMapper memberMapper;
	@Autowired
	private UserService userService;
	@Autowired
	private OrderService orderService;
	@Autowired
	private WxNotifyService wxNotifyService;
	@Autowired
	private CentreIndustryMapper centreIndustryMapper;
	@Autowired
	private CentreService centreService;

	@Value("${Applet.TemplatemsgCreateUserUrl}")
	private String templatemsgCreateUserUrl = "";

	@Override
	public PageUtils<Member> listCommander(Member member, int offset, int limit) {
		logger.info("list commanders > member:{}, offset:{}, limit:{}", member, offset, limit);
		PageUtils<Member> pageUtils = new PageUtils<>();
		HashMap<String, Object> searchMap = new HashMap<String, Object>();
		searchMap.put("isteam", MemberType.NORMAL.getCode());
		searchMap.put("isCheck", MemberCheckType.YES.getCode());
		if (StringUtils.isNotEmpty(member.getCheckContents())) {
			searchMap.put("checkContents", member.getCheckContents());
		}
		if (StringUtils.isNotEmpty(member.getRealname())) {
			searchMap.put("realname", member.getRealname());
		}
		if (StringUtils.isNotEmpty(member.getMobile())) {
			searchMap.put("mobile", member.getMobile());
		}
		if (member.getCentreId() != null) {
			searchMap.put("centreId", member.getCentreId());
		}
		searchMap.put("ORDERLIST", "t.createtime desc");
		int total = memberMapper.getCountByWhere2(searchMap);
		if (total > 0) {
			logger.info("list commanders, total size:{}", total);
			pageUtils.setTotal(total);
			List<Member> memberList = memberMapper.getListByWhere2(searchMap, new RowBounds(offset, limit));
			pageUtils.setRows(memberList);
		} else {
			logger.info("list commanders not found");
			pageUtils.setRows(new ArrayList<>());
		}
		return pageUtils;
	}

	@Override
	public PageUtils<Member> listCloseCommander(Member member, int offset, int limit) {
		logger.info("list closeCommander > member:{}, offset:{}, limit:{}", member, offset, limit);
		PageUtils<Member> pageUtils = new PageUtils<>();
		HashMap<String, Object> searchMap = new HashMap<String, Object>();
		searchMap.put("isteam", MemberType.NORMAL.getCode());
		//searchMap.put("closeTime", DateType.GLWZDATE);
		//数据库导入过来的数据全部有默认的关闭时间 而且全部是 1970-01-01 08:00:00 导致查询关闭会员有问题
		searchMap.put("closeTime", "2017-01-01 00:00:00");
		if (StringUtils.isNotEmpty(member.getRealname())) {
			searchMap.put("realname", member.getRealname());
		}
		if (StringUtils.isNotEmpty(member.getMobile())) {
			searchMap.put("mobile", member.getMobile());
		}
		if (member.getCentreId() != null) {
			searchMap.put("centreId", member.getCentreId());
		}
		searchMap.put("ORDERLIST", "t.close_time desc");
		int total = memberMapper.getCountByWhere2(searchMap);
		if (total > 0) {
			logger.info("list closeCommander, total size:{}", total);
			pageUtils.setTotal(total);
			List<Member> memberList = memberMapper.getListByWhere2(searchMap, new RowBounds(offset, limit));
			pageUtils.setRows(memberList);
		} else {
			logger.info("list closeCommander not found");
			pageUtils.setRows(new ArrayList<>());
		}
		return pageUtils;
	}

	@Override
	public PageUtils<Member> listDyCommander(Member member, int offset, int limit) {
		logger.info("list dyCommander > member:{}, offset:{}, limit:{}", member, offset, limit);
		PageUtils<Member> pageUtils = new PageUtils<>();
		HashMap<String, Object> searchMap = new HashMap<String, Object>();
		searchMap.put("isteam", MemberType.COMMANDER.getCode());
		searchMap.put("sleepTime", DateType.GLWZDATE);
		searchMap.put("sleepEndTime", new Date());
		if (StringUtils.isNotEmpty(member.getRealname())) {
			searchMap.put("realname", member.getRealname());
		}
		if (StringUtils.isNotEmpty(member.getMobile())) {
			searchMap.put("mobile", member.getMobile());
		}
		if (member.getCentreId() != null) {
			searchMap.put("centreId", member.getCentreId());
		}
		searchMap.put("ORDERLIST", "t.sleep_start_time desc");
		int total = memberMapper.getCountByWhere2(searchMap);
		if (total > 0) {
			logger.info("list dyCommander, total size:{}", total);
			pageUtils.setTotal(total);
			List<Member> memberList = memberMapper.getListByWhere2(searchMap, new RowBounds(offset, limit));
			pageUtils.setRows(memberList);
		} else {
			logger.info("list dyCommander not found");
			pageUtils.setRows(new ArrayList<>());
		}
		return pageUtils;
	}

	@Override
	public int cancelCommander(Long id) {
		if (id == null) {
			return 0;
		}
		Member member = new Member();
		member.setId(id);
		member.setSleepTime(null);
		member.setSleepStartTime(null);
		member.setSleepEndTime(null);
		member.setSleepReason("");
		return memberMapper.cancelCommander(member);
	}

	@Override
	public PageUtils<Member> blackListCommander(ListMemberParams listMemberParams, Member member, int offset, int limit) {
		logger.info("list blackListCommander > listMemberParams:{}, member:{}, offset:{}, limit:{}", listMemberParams, member, offset, limit);
		PageUtils<Member> pageUtils = new PageUtils<>();
		HashMap<String, Object> searchMap = new HashMap<String, Object>();
		searchMap.put("status", MemberStatus.PULL_BLACK.getCode());
       /* if(StringUtils.isNotEmpty(listMemberParams.getFollow())){
            searchMap.put("follow", Integer.parseInt(listMemberParams.getFollow()));
        }*/
		if (StringUtils.isNotEmpty(listMemberParams.getStartDate())) {
			searchMap.put("startDate", listMemberParams.getStartDate());
		}
		if (StringUtils.isNotEmpty(listMemberParams.getEndDate())) {
			searchMap.put("endDate", listMemberParams.getEndDate());
		}
		if (StringUtils.isNotEmpty(member.getNickname())) {
			searchMap.put("nickname", member.getNickname());
		}
		if (StringUtils.isNotEmpty(member.getMobile())) {
			searchMap.put("mobile", member.getMobile());
		}
		if (listMemberParams.getCentreId() != null) {
			searchMap.put("centreId", listMemberParams.getCentreId());
		}
		if (listMemberParams.getLiansuoId() != null) {
			searchMap.put("teamid", listMemberParams.getLiansuoId());
		}
		searchMap.put("ORDERLIST", "t.createtime desc");
		int total = memberMapper.getCountByWhere(searchMap);
		if (total > 0) {
			logger.info("list blackListCommander, total size:{}", total);
			pageUtils.setTotal(total);
			List<Member> memberList = memberMapper.getListByWhere(searchMap, new RowBounds(offset, limit));
			pageUtils.setRows(memberList);
		} else {
			logger.info("list blackListCommander not found");
			pageUtils.setRows(new ArrayList<>());
		}
		return pageUtils;
	}

	@Override
	public int removeBlack(Long id) {
		if (id == null) {
			return 0;
		}
		Member member = new Member();
		member.setId(id);
		member.setStatus(MemberStatus.CHECK_PASS.getCode());
		return memberMapper.updateByPrimaryKeySelective(member);
	}

	@Override
	public PageUtils<Member> noCheckCommander(ListMemberParams listMemberParams, Member member, int offset, int limit) {
		logger.info("list noCheckCommander > listMemberParams:{}, member:{}, offset:{}, limit:{}", listMemberParams, member, offset, limit);
		PageUtils<Member> pageUtils = new PageUtils<>();
		HashMap<String, Object> searchMap = new HashMap<String, Object>();
		int[] isteams = {MemberType.INVITE_TO_COMMANDER.getCode(), MemberType.APPLY_TO_COMMANDER.getCode(), MemberType.CHECKED_NO_OPEN.getCode()};
		searchMap.put("isteams", isteams);
		if (StringUtils.isNotEmpty(listMemberParams.getStartDate())) {
			searchMap.put("startDate", listMemberParams.getStartDate());
		}
		if (StringUtils.isNotEmpty(listMemberParams.getEndDate())) {
			searchMap.put("endDate", listMemberParams.getEndDate());
		}
		if (member.getTeamNum() != null) {
			searchMap.put("teamNum", member.getTeamNum());
		}
		if (StringUtils.isNotEmpty(member.getNickname())) {
			searchMap.put("nickname", member.getNickname());
		}
		if (StringUtils.isNotEmpty(member.getMobile())) {
			searchMap.put("mobile", member.getMobile());
		}
		if (listMemberParams.getCentreId() != null) {
			searchMap.put("centreId", listMemberParams.getCentreId());
		}
		if (StringUtils.isNotEmpty(member.getRealname())) {
			searchMap.put("realname", member.getRealname());
		}
		searchMap.put("ORDERLIST", "t.s_time");
		int total = memberMapper.getCountByWhere2(searchMap);
		if (total > 0) {
			logger.info("list noCheckCommander, total size:{}", total);
			pageUtils.setTotal(total);
			List<Member> memberList = memberMapper.getListByWhere2(searchMap, new RowBounds(offset, limit));
//            for (Member member1 : memberList) {
//                centreTerminalMapper.selectByIdIn();
//                centreTerminalMapper.
//            }
			pageUtils.setRows(memberList);
		} else {
			logger.info("list noCheckCommander not found");
			pageUtils.setRows(new ArrayList<>());
		}
		return pageUtils;
	}

	@Override
	public int batchUpdates(String ids, Integer teamNum) {
		if (StringUtils.isEmpty(ids) || teamNum == null) {
			return 0;
		}
		int flag = 0;
		String[] id = ids.split(",");
		for (int i = 0; i < id.length; i++) {
			Member member = new Member();
			member.setId(Long.parseLong(id[i]));
			member.setTeamNum(teamNum);
			int n = memberMapper.updateByPrimaryKeySelective(member);
			if (n > 0) {
				flag++;
			}
		}
		return flag;
	}

	@Override
	public int batchExamine(String ids, Integer isteam) {
		if (StringUtils.isEmpty(ids) || isteam == null) {
			return 0;
		}
		int flag = 0;
		String[] id = ids.split(",");
		for (int i = 0; i < id.length; i++) {
			Member member = new Member();
			member.setId(Long.parseLong(id[i]));
			member.setIsteam(isteam);
			member.setCheckTime(new Date());
			//-------↓↓↓↓↓↓↓↓审核通过将自己设置为上次购买门店↓↓↓↓↓↓↓↓↓--------
			Member m = memberMapper.selectByPrimaryKey(Long.parseLong(id[i]));
			String name = "";
			Member memberAll = memberMapper.selectByPrimaryKey(member.getId());
			if (PayStatus.PAY_SUCCESS.getCode() != memberAll.getPayStatus()) {
				throw new BDException("请支付！");
			}
			if (m != null) {
				if (StringUtils.isNotEmpty(m.getRealname())) {
					name = m.getRealname();
				} else {
					if (StringUtils.isNotEmpty(m.getNickname())) {
						name = m.getNickname();
					}
				}
				member.setUpshopTid(m.getId());
				member.setUpshopName(name);
				member.setTeamid(m.getId());
			}
			//-------↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑--------
			int n = memberMapper.updateByPrimaryKeySelective(member);
			if (n > 0) {
				flag++;
				//生成后台门店管理账号
				String adminName = m.getMobile() + m.getCentreId();

				if (!userService.checkExit(adminName)) {
					SysUser user = new SysUser();
					user.setName(adminName);
					user.setNickname(name);
					user.setPassword(SystemConstant.DEFAULT_PWD_USER.getConstants());
					user.setPhone(member.getMobile());
					user.setCentreId(member.getCentreId());
					user.setFlag(PermisFlag.FLAG_SHOP);
					user.setTeamId(member.getId());

					Centre centre = centreService.getCentreById(m.getCentreId());

					String roleId = SystemConstant.USER_ID_SHOP_LOCAL_ADMIN.getConstants();
					if (MemberStoresApplicationWayEnum.LOCAL_LIFE.getCode().equals(memberAll.getStoresApplicationWay())) {
						roleId = SystemConstant.USER_ID_SHOP_LOCAL_ADMIN.getConstants();
					} else {
						//小程序申请的门店需要查询对应行业的角色id
						if (centre != null && centre.getIndustryId() != null) {
							CentreIndustry centreIndustry = centreIndustryMapper.selectByPrimaryKey(Long.valueOf(centre.getIndustryId()));
							if (centreIndustry != null && centreIndustry.getStoreRoleId() != null) {
								roleId = centreIndustry.getStoreRoleId().toString();
							}
						}
					}
					//门店
					userService.saveUser(user, roleId);
				} else {
					SysUser user = userService.getUserByName(adminName);
					Centre centre = centreService.getCentreById(member.getCentreId());
					String roleId = SystemConstant.USER_ID_SHOP_ADMIN.getConstants();
					if (MemberStoresApplicationWayEnum.LOCAL_LIFE.getCode().equals(memberAll.getStoresApplicationWay())) {
						roleId = SystemConstant.USER_ID_SHOP_LOCAL_ADMIN.getConstants();
					} else {
						//小程序申请的门店需要查询对应行业的角色id
						if (centre != null && centre.getIndustryId() != null) {
							CentreIndustry centreIndustry = centreIndustryMapper.selectByPrimaryKey(Long.valueOf(centre.getIndustryId()));
							if (centreIndustry != null && centreIndustry.getStoreRoleId() != null) {
								roleId = centreIndustry.getStoreRoleId().toString();
							}
						}
					}
					//修改所属门店
					user.setTeamId(member.getId());
					List<Long> list = new ArrayList<>();
					list.add(Long.valueOf(roleId));
					user.setRoleIds(list);
					userService.updateUser(user);
				}
				//通知用户
				String msgContent = "您的后台管理帐号为：" + adminName + "，密码为：" + SystemConstant.DEFAULT_PWD_USER.getConstants() + "，欢迎您的加入！";
				// 发送短信
				try {
					String newTemplatemsgCreateUserUrl = templatemsgCreateUserUrl + "?centerId=" + member.getCentreId();
					msgContent = msgContent + "后台管理系统入口：" +newTemplatemsgCreateUserUrl;
					//todo 短信通道暂无
//					shiYuanSmsClient.send(member.getMobile(), msgContent);

					Map<String, String> map = new HashMap<>();
					map.put("url", newTemplatemsgCreateUserUrl);
					map.put("accounts", adminName);
					map.put("accountsStr", "用户名：" + adminName);
					map.put("pwdStr", "您的密码为" + SystemConstant.DEFAULT_PWD_USER.getConstants());
					map.put("pwd", SystemConstant.DEFAULT_PWD_USER.getConstants());
					map.put("type", "门店【" + member.gettXiaoqu() + "】后台管理帐号创建");
					map.put("createdDate", DateUtil.convertDateToStr(new Date(), DateUtil.yyyy_MM_dd_HH_mm_ss));
					map.put("type0", "门店【" + member.gettXiaoqu() + "】后台管理帐号创建成功");
					String str = "";
					str += "用户名: " + adminName + ",\n";
					str += "用户密码: " + SystemConstant.DEFAULT_PWD_USER.getConstants() + ",\n";
					map.put("remark", str);
					map.put("status", "创建成功,已启用!");
					//发送模版消息
					orderService.sendAccountsTemplateToUser(member.getCentreId(), member.getId(), map);

					//发送公众号文本消息
					if (ValidateUtil.isNotEmptyString(member.getOpenid())) {
						//消息通知
						WxNotifyParam notifyParam = new WxNotifyParam();
						notifyParam.setMessageType(WxMessageType.MESSAGE_TYPE_TEXT.getType());//文本消息
						notifyParam.setCenterId(member.getCentreId());
						notifyParam.setGzhOpenId(member.getOpenid());
						notifyParam.setTeminal(WxTerminal.TERMINAL_GZH.getTerminal());
						notifyParam.setContent(msgContent);
						wxNotifyService.sendNotify(notifyParam);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return flag;
	}

	@Override
	public List<Member> noCheckCommander(ListMemberParams listMemberParams, Member member) {
		logger.info("Export noCheckCommander > listMemberParams:{}, member:{}", listMemberParams, member);
		HashMap<String, Object> searchMap = new HashMap<String, Object>();
		int[] isteams = {MemberType.INVITE_TO_COMMANDER.getCode(), MemberType.APPLY_TO_COMMANDER.getCode(), MemberType.CHECKED_NO_OPEN.getCode()};
		searchMap.put("isteams", isteams);
		if (StringUtils.isNotEmpty(listMemberParams.getStartDate())) {
			searchMap.put("startDate", listMemberParams.getStartDate());
		}
		if (StringUtils.isNotEmpty(listMemberParams.getEndDate())) {
			searchMap.put("endDate", listMemberParams.getEndDate());
		}
		if (member.getTeamNum() != null) {
			searchMap.put("teamNum", member.getTeamNum());
		}
		if (StringUtils.isNotEmpty(member.getNickname())) {
			searchMap.put("nickname", member.getNickname());
		}
		if (StringUtils.isNotEmpty(member.getMobile())) {
			searchMap.put("mobile", member.getMobile());
		}
		if (listMemberParams.getCentreId() != null) {
			searchMap.put("centreId", listMemberParams.getCentreId());
		}
		searchMap.put("ORDERLIST", "t.createtime desc");
		int total = memberMapper.getCountByWhere2(searchMap);
		if (total > 0) {
			logger.info("Export noCheckCommander, total size:{}", total);
			List<Member> memberList = memberMapper.getListByWhere2(searchMap);
			return memberList;
		} else {
			logger.info("Export noCheckCommander not found");
			return null;
		}
	}

	@Override
	public List<Member> listCommander(Member member) {
		logger.info("Export commanders > member:{}", member);
		HashMap<String, Object> searchMap = new HashMap<String, Object>();
		searchMap.put("isteam", MemberType.NORMAL.getCode());
		searchMap.put("isCheck", MemberCheckType.YES.getCode());
		if (StringUtils.isNotEmpty(member.getCheckContents())) {
			searchMap.put("checkContents", member.getCheckContents());
		}
		if (StringUtils.isNotEmpty(member.getRealname())) {
			searchMap.put("realname", member.getRealname());
		}
		if (StringUtils.isNotEmpty(member.getMobile())) {
			searchMap.put("mobile", member.getMobile());
		}
		if (member.getCentreId() != null) {
			searchMap.put("centreId", member.getCentreId());
		}
		searchMap.put("ORDERLIST", "t.createtime desc");
		int total = memberMapper.getCountByWhere2(searchMap);
		if (total > 0) {
			logger.info("Export commanders, total size:{}", total);
			List<Member> memberList = memberMapper.getListByWhere2(searchMap);
			return memberList;
		} else {
			logger.info("Export commanders not found");
			return null;
		}
	}

	@Override
	public List<Member> listCloseCommander(Member member) {
		logger.info("Export closeCommander > member:{}", member);
		HashMap<String, Object> searchMap = new HashMap<String, Object>();
		searchMap.put("isteam", MemberType.NORMAL.getCode());
		//searchMap.put("closeTime", DateType.GLWZDATE);
		//数据库导入过来的数据全部有默认的关闭时间 而且全部是 1970-01-01 08:00:00 导致查询关闭会员有问题
		searchMap.put("closeTime", "2017-01-01 00:00:00");
		if (StringUtils.isNotEmpty(member.getRealname())) {
			searchMap.put("realname", member.getRealname());
		}
		if (StringUtils.isNotEmpty(member.getMobile())) {
			searchMap.put("mobile", member.getMobile());
		}
		if (member.getCentreId() != null) {
			searchMap.put("centreId", member.getCentreId());
		}
		searchMap.put("ORDERLIST", "t.close_time desc");
		int total = memberMapper.getCountByWhere2(searchMap);
		if (total > 0) {
			logger.info("Export closeCommander, total size:{}", total);
			List<Member> memberList = memberMapper.getListByWhere2(searchMap);
			return memberList;
		} else {
			logger.info("Export closeCommander not found");
			return null;
		}
	}

	@Override
	public List<Member> listDyCommander(Member member) {
		logger.info("Export dyCommander > member:{}", member);
		HashMap<String, Object> searchMap = new HashMap<String, Object>();
		searchMap.put("isteam", MemberType.COMMANDER.getCode());
		searchMap.put("sleepTime", DateType.GLWZDATE);
		searchMap.put("sleepEndTime", new Date());
		if (StringUtils.isNotEmpty(member.getRealname())) {
			searchMap.put("realname", member.getRealname());
		}
		if (StringUtils.isNotEmpty(member.getMobile())) {
			searchMap.put("mobile", member.getMobile());
		}
		if (member.getCentreId() != null) {
			searchMap.put("centreId", member.getCentreId());
		}
		searchMap.put("ORDERLIST", "t.createtime desc");
		int total = memberMapper.getCountByWhere2(searchMap);
		if (total > 0) {
			logger.info("Export dyCommander, total size:{}", total);
			List<Member> memberList = memberMapper.getListByWhere2(searchMap);
			return memberList;
		} else {
			logger.info("Export dyCommander not found");
			return null;
		}
	}

	@Override
	public IsteamDesc getIsteamDesc(String isteamDesc) {
		IsteamDesc desc = new IsteamDesc();
		try {
			if (StringUtils.isEmpty(isteamDesc)) {
				desc.setRemark("");
				desc.setIdCardZ("");
				desc.setIdCardF("");
				desc.setGsLicense("");
				desc.setSpLicense("");
				desc.setStore("");
				return desc;
			}
			String remark = JSONObject.parseObject(isteamDesc).getString("remark");
			desc.setRemark(remark);
			JSONObject jsonObject = JSON.parseObject(isteamDesc);
			JSONArray images = jsonObject.getJSONArray("images");
			if (images != null && images.size() >= 5) {
				desc.setIdCardZ((String) images.get(0) != null ? (String) images.get(0) : "");
				desc.setIdCardF((String) images.get(1) != null ? (String) images.get(1) : "");
				desc.setGsLicense((String) images.get(2) != null ? (String) images.get(2) : "");
				desc.setSpLicense((String) images.get(3) != null ? (String) images.get(3) : "");
				desc.setStore((String) images.get(4) != null ? (String) images.get(4) : "");
			}
		} catch (Exception e) {
			logger.info("获取营业执照相关数据错误, isteamDesc:{}", isteamDesc);
			desc.setRemark("");
			desc.setIdCardZ("");
			desc.setIdCardF("");
			desc.setGsLicense("");
			desc.setSpLicense("");
			desc.setStore("");
			return desc;
		}
		return desc;
	}

}
